package cn.jichangxiu.auth.service;

import cn.jichangxiu.auth.client.UCenterClient;
import cn.jichangxiu.auth.model.Auth;
import cn.jichangxiu.auth.model.UserJWT;
import cn.jichangxiu.common.ucenter.entity.Authority;
import cn.jichangxiu.common.ucenter.entity.User;
import cn.jichangxiu.common.web.model.response.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UCenterClient uCenterClient;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        ArrayList<Auth> auths = new ArrayList();
        User user = null;
        R r = uCenterClient.getUserByAccount(account);

        if (r.getResult() != null && r.getResult().getData() !=null && r.getResult().getData().get(0) != null) {
            user = JSON.parseObject(JSON.toJSONString(r.getResult().getData().get(0)), User.class);
        }
        if (user != null) {
            R r1 = uCenterClient.getUserAuths(user.getId());
            if (r1.getResult().getData() != null) {
                JSONArray jsonArray = JSON.parseObject(JSON.toJSONString(r1.getResult().getData()), JSONArray.class);
                if (jsonArray.size() > 0){
                    jsonArray.forEach(auth -> {
                        Authority a = JSON.parseObject(JSON.toJSONString(auth), Authority.class);
                        auths.add(new Auth(a.getCode()));
                    });
                }
                UserJWT jwt = new UserJWT(user.getId(), user.getAccount(), user.getPassword(), auths);
                jwt.setAvatar(user.getAvatar());
                jwt.setNickname(user.getNickname());
                jwt.setUserDesc(user.getUserDesc());
                jwt.setInfoId(user.getInfoId());
                return jwt;
            }
        }
        return null;
    }
}